<template>
  <div class="content1">
    <t-dialog
        placement="center"
        width="504"
        v-model:visible="visible"
        header="批量导入"
        :onClose="onClose"
        destroy-on-close
    >
      <template #body>
<!--        <t-radio-group default-value="1" @change="onChange">-->
<!--          <t-radio value="1">新增</t-radio>-->
<!--          <t-radio value="2">更新</t-radio>-->
<!--        </t-radio-group>-->

        <div class="failBox" v-if="uploadError">
          <div class="info">错误报告</div>
          <div class="downLoad" @click="downError">点击下载错误报告 </div>
        </div>

        <div class="uploadBox">
          <t-upload
              ref="uploadRef"
              v-model="files"
              :autoUpload="autoUpload"
              withCredentials
              method="POST"
              :headers="queryHeaders"
              :theme="display"
              :data="queryBody"
              :abridge-name="[10, 8]"
              :draggable="true"
              :action="url"
              :before-upload="beforeUpload"
              @success="handleSuccess"
              :showUploadProgress="true"
              @progress="onProgress"
              @fail="handleFail"
          >
            <div v-if="files && files.length > 0" class="upload_text">
              <div class="fileName">
                {{ files[0].name }}
                <span v-if="isShowLoading" style="color: rgba(0, 82, 217, 1)"><LoadingIcon/></span>
                <svg-icon
                    v-if="uploadError"
                    :name="'icon-uploadError'"
                ></svg-icon>
              </div>
              <div class="fileSize">文件大小：{{ Math.round(files[0].size / 1024) }}k</div>
            </div>
            <div v-else class="upload_empty">
              点击上传 /  将文件拖拽到此区域
            </div>
          </t-upload>
          <span v-if="showDel" class="delBtn" @click="deleteFile">
            {{ uploadError ? '重新上传' : '删除'}}
          </span>
        </div>
        <div v-if="props.templateText !== ''" class="uploadModel" @click="handleTemplateDownload">
          <svg-icon
              :name="'icon-upload'"
              class-name="upload-svg-icon"
          ></svg-icon>
          <span class="text">{{ props.templateText }}</span>

        </div>
        <div v-if="props.templateText === ''" style="height: 16px"></div>
        <div class="btnBox">
          <t-button class="resetBtn" @click="close" variant="text">取消</t-button>
          <t-button class="uploadBtn" theme="primary" variant="base" :disabled="files.length === 0" @click="uploadFiles">开始上传</t-button>
        </div>
      </template>
    </t-dialog>

  </div>
</template>

<script lang="jsx" setup>
import { ref, getCurrentInstance, watch, reactive, onMounted  } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import auth from '@/utils/auth.js'
import { testUpload, keywordUpload } from '@/api/system/upload.js'
import { saveAs } from 'file-saver'
// import {formData} from "../../views/qualityResult/hooks/page";
import {tagUpload, templateUpload, transitionUpload} from "../../api/system/upload";
import {
  LoadingIcon
} from 'tdesign-icons-vue-next';

const emit = defineEmits()
const props = defineProps({
  openUpload: {
    type: Boolean,
    default: false
  },
  CloseUpload: {
    type: Function,
    default: () => {}
  },
  templateText: {
    type: String,
    default: ''
  },
  downloadTemplate: { // 下载模版事件
    type: Function,
    default: () => {}
  },
  queryBody: { // 上传请求体
    type: Object,
    default: {}
  },
  uploadUrl: { // action
    type: String,
    default: ''
  },
  accept: {
    type: String,
    default: ''
  }
})

const queryHeaders = ref({
  Authorization: "Bearer " + auth.getToken()
})
// 弹窗开关
const visible = ref(false)
const url = ref()
watch(() => props.openUpload, (newVal, oldVal) => {
  visible.value = newVal
  url.value = import.meta.env.VITE_APP_API + props.uploadUrl
})
const onClose = () => {
  close()
}
// radio 按钮
const onChange = (checkedValues) => {
  console.log('checkedValues', checkedValues)
}
// 上传
const display = ref('custom');
const files = ref([]);
const uploadRef = ref();
const progress = ref(0);
const autoUpload = ref(false);
const fileSize = ref(0)

const showDel = ref(false)

const beforeUpload = (file) => {
    console.log('打印看看file', file);
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.accept.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      MessagePlugin.error(`文件格式不正确, 请上传${props.accept}格式文件!`)
      return false;
    }
    showDel.value = true
};
const deleteFile = () => {
  showDel.value = false
  uploadError.value = false
  files.value = []
}


// 上传成功
const handleSuccess = ({ file,response }) => {
  console.log('上传成功回调函数', response)
  // MessagePlugin.success(`文件 ${file.name} 上传成功`);
  if(file.response.code) { // 导入成功
  } else { // 导入失败
    // console.log('file.response', file.response.replace("\"","").replace("\"",""))
    const blob = new Blob([response], {
      // type: 'application/vnd.ms-excel;charset=utf-8'
      type: 'application/octet-stream'
    })

    // console.log('blob', blob)
    // saveAs(blob, '错误报告.xlsx')
    // // const blob = dataURItoBlob(
    // //     "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," +
    // //     file.response
    // // )

    const url = URL.createObjectURL(blob) //把blob对象转成一个url
    console.log('url', url)

    // //创建一个a标签
    // const a = document.createElement("a");
    // a.href = url; //给a标签上的href属性加上地址
    // a.download = `错误报告${new Date().getTime()}.xlsx`; //下载名称
    // document.body.appendChild(a); //将a标签添加到文档对象中
    // a.click(); //调点击事件
    // document.body.removeChild(a); // 一次性的，用完就删除a标签

    // const url = URL.createObjectURL(file.response)
    console.log('看看这是什么', blob)
    // const blob2 = new Blob([blob])
    // console.log('sdfsdfdsf', blob2);
    saveAs(url, '666.xlsx')
  }
};


// 上传失败
const handleFail = ({ file }) => {
  console.log('上传失败回调函数', file)
  // MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

// 下载模版
const handleTemplateDownload = () => {
  props.downloadTemplate()
}

const uploadError = ref(null)
const errorFile = ref(null)
const isShowLoading = ref(false) // 上传中loading
const uploadFiles = () => {
  let formDate = new FormData()
  formDate.append('file', files.value[0].raw)
  formDate.append('projectId', 0)
  isShowLoading.value = true

  if(props.uploadUrl === '/word/import') {
    workImport(formDate)
  } else if (props.uploadUrl === '/keyword/import') {
    keywordImport(formDate)
  } else if (props.uploadUrl === '/transition/import') {
    transitionImport(formDate)
  } else if (props.uploadUrl === '/tag/import') {
    tagImport(formDate)
  } else if (props.uploadUrl === '/template/import') {
    templateImport(formDate)
  }
};

// 词类导入
const workImport = (formDate) => {
  testUpload(formDate).then(res => {
    isShowLoading.value = false
    if(res.size !== 0) {
      uploadError.value = true
      errorFile.value = res
      return
    }
    visible.value = false
    showDel.value = false
    MessagePlugin.success('文件上传成功')
    deleteFile()
    emit('closeUpload', false)
  })
}
// 关键词导入
const keywordImport = (formDate) => {
  keywordUpload(formDate).then(res => {
    isShowLoading.value = false
    if(res.size !== 0) {
      uploadError.value = true
      errorFile.value = res
      return
    }
    visible.value = false
    showDel.value = false
    MessagePlugin.success('文件上传成功')
    deleteFile()
    emit('closeUpload', false)
  })
}
// 转写矫正导入
const transitionImport = (formDate) => {
  transitionUpload(formDate).then(res => {
    isShowLoading.value = false
    if(res.size !== 0) {
      uploadError.value = true
      errorFile.value = res
      return
    }
    visible.value = false
    showDel.value = false
    MessagePlugin.success('文件上传成功')
    deleteFile()
    emit('closeUpload', false)
  })
}
// 标签导入
const tagImport = (formDate) => {
  tagUpload(formDate).then(res => {
    isShowLoading.value = false
    if(res.size !== 0) {
      uploadError.value = true
      errorFile.value = res
      return
    }
    visible.value = false
    showDel.value = false
    MessagePlugin.success('文件上传成功')
    deleteFile()
    emit('closeUpload', false)
  })
}
// 质检模版导入
const templateImport = (formData) => {
  templateUpload(formData).then(res => {
    isShowLoading.value = false
    console.log('质检模版导入',res)
    if (res.type === 'application/json') { // application/json - 错误信息
      console.log('失败接口：', res) // 失败接口：Blob {size: 183, type: 'application/json'}
      const data = new FileReader() // 文件API用于读取文件
      data.readAsText(res, 'utf-8') // 将文件以utf-8编码方式读取，结果为string文本
      data.onload = () => { // 文件读取完成触发
        let dataResult = data.result // result为读取后的结果
        const parseObj = JSON.parse(dataResult) // 将读取后的string文本转为json数据
        if(parseObj.code === 0) {
          MessagePlugin.success('文件上传成功')
        } else {
          MessagePlugin.error(parseObj.msg)
        }

        deleteFile()
        emit('closeUpload', false)
      }
    }
  }).catch(error => {
    console.log('质检模版导入错误', error)
  })
}

const downError = () => {
  saveAs(errorFile.value,'错误报告.xlsx')
  // close()
}

// 关闭弹窗
const close = () => {
  deleteFile()
  files.value = []
  deleteFile()
  emit('closeUpload', false)
}

const onProgress = (file) => {
  console.log('progress', file)
}


const dataURItoBlob = (base64Data) => {
  let byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = window.atob(base64Data.split(',')[1]);
  } else {
    byteString = window.unescape(base64Data.split(',')[1]);
  }
  let mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  let ia = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], { type: mimeString });
}

</script>

<style lang="scss" scoped>
.content1 {
  :deep(.t-dialog__ctx .t-dialog) {
    padding: 26px 30px 0 30px !important;
    .t-dialog__header {
      .t-dialog__header-content {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.9);
      }
    }
    .t-dialog__body {
      // padding-top: 39px;
      padding-bottom: 20px;
      .t-radio-group {
        .t-radio__label {
          font-size: 12px;
          font-weight: 400;
          color: rgba(92, 91, 91, 1);
        }
      }
      .failBox {
        // margin-top: 20px;
        height: 28px;
        border-radius: 6px;
        background: rgba(254, 240, 240, 1);
        padding: 3px 11px 3px 11px;
        color: rgba(227, 77, 89, 1);
        display: flex;
        .info {
          font-size: 13px;
          font-weight: 400;
        }
        .downLoad {
          margin-left: auto;
          font-size: 13px;
          font-weight: 400;
          text-decoration-line: underline;
          color: rgba(227, 77, 89, 1);
          cursor: pointer;

        }
      }
      .uploadBox {
        position: relative;
        .delBtn {
          position: absolute;
          right: 32px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          font-size: 14px;
          font-weight: 400;
          color: rgba(30, 117, 254, 1);
        }
      }
      .t-upload {
        margin-top: 20px;
        .t-upload__dragger {
          padding: 0 32px;
          width: 100%;
          height: 133px;
          border-radius: 6px;
          .customBox {
            font-size: 16px;
            font-weight: 400;
            color: rgba(49, 129, 254, 1);
            span {
              display: inline-block;
              margin: 0 5px;
            }
          }
        }
        .t-upload__dragger:hover {
          background: rgba(247, 250, 255, 1);
          border: 1px dashed rgba(30, 117, 254, 1);
        }
        .t-upload__trigger {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .t-upload__dragger-progress {
          align-items: center;
        }
        .t-upload__dragger-progress-info {
          .t-upload__dragger-btns {
            display: none;
          }
        }
        .t-upload__dragger-progress-info small:nth-child(3) {
          display: none;
        }
      }
      .uploadModel {
        margin-top: 8px;
        align-items: center;
        vertical-align: middle;
        display: inline-block;
        .upload-svg-icon {
          height: 16px;
          width: 16px;
          display: inline-block;
          cursor: pointer;
          vertical-align: middle;
        }
        .text {
          font-size: 12px;
          font-weight: 400;
          text-decoration-line: underline;
          color: rgba(30, 117, 254, 1);
          cursor: pointer;
          padding-left: 4px;
        }
      }
      .btnBox {
        text-align: right;
        .resetBtn {
          width: 60px;
          height: 28px;
          background: rgba(255, 255, 255, 1);
          color: rgba(0, 0, 0, 0.9);
          font-size: 14px;
          font-weight: 400;
          margin-right: 8px;
        }
        .uploadBtn {
          width: 88px;
          height: 28px;
          opacity: 1;
          background: rgba(30, 117, 254, 1);
          color: rgba(255, 255, 255, 0.9);
          font-size: 14px;
          font-weight: 400;
          border: none;
        }
         .t-is-disabled {
           color: rgba(255, 255, 255, 0.9);
           background: rgba(212, 227, 252, 1) !important;
         }
      }
    }
    .t-dialog__footer {
      display: none;
    }
  }
}
:deep(.t-upload__trigger) {
  justify-content: left !important;
}
.upload_empty {
  font-size: 16px;
  font-weight: 400;
  color: rgba(49, 129, 254, 1);
  width: 100%;
  text-align: center;
}
.upload_text {
  .fileName {
    margin-bottom: 4px;
    font-size: 14px;
    font-weight: 600;
    color: rgba(92, 91, 91, 1);
    .svg-icon {
      height: 14px;
      width: 14px;
    }
  }
  .fileSize {
    margin-top: 4px;
    font-size: 13px;
    font-weight: 400;
    color: rgba(110, 110, 110, 0.9);
  }
}
</style>
